package com.mzba.easy.weibo.ui;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.actionbarsherlock.app.SherlockFragment;
import com.mzba.easy.weibo.MainActivity;
import com.mzba.easy.weibo.R;
import com.mzba.easy.weibo.db.CommentEntry;
import com.mzba.easy.weibo.db.CommentGson;
import com.mzba.easy.weibo.db.CommentsTimelineTable;
import com.mzba.easy.weibo.util.AppContext;
import com.mzba.easy.weibo.util.BasicUIEvent;
import com.mzba.easy.weibo.util.UICore;
import com.mzba.easy.weibo.util.WeiboManager;
import com.mzba.easy.weibo.widget.CustomListView;

/**
 * 
 * @author 06peng
 *
 */
public class CommentsTimeLineFragment extends SherlockFragment implements BasicUIEvent, Callback {
	
	private CustomListView listView;
	private LinearLayout localView;
	private Handler handler;
	private WeiboManager weiboManager;
	private List<CommentEntry> timelineEntries;
	private int count = 20;
	private int page = 1;
	private String since_id = "0";
	
	private final int get_comments_timeline = 1;
	private final int refresh_timeline = 2;
	private final int load_more = 3;
	
	private boolean isLoading;
	private CommentTimelineAdapter adapter;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		handler = new Handler(this);
		weiboManager = new WeiboManager(getActivity());
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_layout, null);
		if (localView != null) {
			localView.removeAllViews();
		}
		localView = (LinearLayout) view.findViewById(R.id.pager);
		if (listView == null) {
			listView = (CustomListView) inflater.inflate(R.layout.listview_layout, null);
		}
		listView.setSelector(R.drawable.list_bg_selector);
		listView.setonRefreshListener(new CustomListView.OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				menuRefresh();
			}
		});
		listView.setonLoadListener(new CustomListView.OnLoadListener() {
			
			@Override
			public void onLoad() {
				page++;
				UICore.eventTask(CommentsTimeLineFragment.this, (MainActivity) getActivity(), load_more, null);
			}
		});
		return view;
	}
	
	public void menuRefresh() {
		page = 1;
		UICore.eventTask(CommentsTimeLineFragment.this, (MainActivity) getActivity(), refresh_timeline, null);
	}
	
	public void getCommentFragment() {
		if (timelineEntries != null) {
			timelineEntries.clear();
			if (adapter != null) {
				adapter.notifyDataSetChanged();
			}
		}
		UICore.eventTask(this, (MainActivity) getActivity(), get_comments_timeline, null);
	}

	@Override
	public void execute(int mes, Object obj) {
		try {
			switch (mes) {
			case get_comments_timeline:
				getCommentTimeline();
				handler.sendEmptyMessage(get_comments_timeline);
				break;
			case refresh_timeline:
				refreshCommentTimeline();
				handler.sendEmptyMessage(get_comments_timeline);
				break;
			case load_more:
				loadMoreTimeline();
				handler.sendEmptyMessage(load_more);
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void getCommentTimeline() {
		try {
			CommentsTimelineTable table = new CommentsTimelineTable();
			if (timelineEntries != null) {
				timelineEntries.clear();
			}
			page = 1;
			since_id = "0";
			isLoading = false;
			switch (((MainActivity) getActivity()).groupItem) {
			case 0:
				timelineEntries = table.getAllComments("all");
				if (timelineEntries == null || timelineEntries.isEmpty()) {
					CommentGson timeline = weiboManager.getCommentsTimeline(AppContext.comment_timeline, count, page, since_id);
					timelineEntries = timeline.getComments();
					if (timelineEntries != null && timelineEntries.size() > 0) {
						since_id = timelineEntries.get(0).getId();
					}
					table.save(timelineEntries, "all");
				}
				break;
			case 1:
				timelineEntries = table.getAllComments("tome");
				if (timelineEntries == null || timelineEntries.isEmpty()) {
					CommentGson timeline = weiboManager.getCommentsTimeline(AppContext.comment_timeline_tome, count, page, since_id);
					timelineEntries = timeline.getComments();
					if (timelineEntries != null && timelineEntries.size() > 0) {
						since_id = timelineEntries.get(0).getId();
					}
					table.save(timelineEntries, "tome");
				}
				break;
			case 2:
				timelineEntries = table.getAllComments("byme");
				if (timelineEntries == null || timelineEntries.isEmpty()) {
					CommentGson timeline = weiboManager.getCommentsTimeline(AppContext.comment_timeline_byme, count, page, since_id);
					timelineEntries = timeline.getComments();
					if (timelineEntries != null && timelineEntries.size() > 0) {
						since_id = timelineEntries.get(0).getId();
					}
					table.save(timelineEntries, "byme");
				}
				break;
			case 3:
				timelineEntries = table.getAllComments("mentionme");
				if (timelineEntries == null || timelineEntries.isEmpty()) {
					CommentGson timeline = weiboManager.getCommentsTimeline(AppContext.comment_timeline_mentionme, count, page, since_id);
					timelineEntries = timeline.getComments();
					if (timelineEntries != null && timelineEntries.size() > 0) {
						since_id = timelineEntries.get(0).getId();
					}
					table.save(timelineEntries, "mentionme");
				}
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void refreshCommentTimeline() {
		try {
			CommentsTimelineTable table = new CommentsTimelineTable();
			CommentGson timeline = null;
			List<CommentEntry> newTimelineEntries = null;
			page = 1;
			switch (((MainActivity) getActivity()).groupItem) {
			case 0:
				isLoading = false;
				timeline = weiboManager.getCommentsTimeline(AppContext.comment_timeline, count, page, since_id);
				newTimelineEntries = timeline.getComments();
				if (newTimelineEntries != null && !newTimelineEntries.isEmpty()) {
					List<CommentEntry> temp = new ArrayList<CommentEntry>(timelineEntries);
					timelineEntries.clear();
					timelineEntries.addAll(newTimelineEntries);
					timelineEntries.addAll(temp);
					table.save(timelineEntries, "all");
					since_id = timelineEntries.get(0).getId();
				}
				break;
			case 1:
				isLoading = false;
				timeline = weiboManager.getCommentsTimeline(AppContext.comment_timeline_tome, count, page, since_id);
				newTimelineEntries = timeline.getComments();
				if (newTimelineEntries != null && !newTimelineEntries.isEmpty()) {
					List<CommentEntry> temp = new ArrayList<CommentEntry>(timelineEntries);
					timelineEntries.clear();
					timelineEntries.addAll(newTimelineEntries);
					timelineEntries.addAll(temp);
					table.save(timelineEntries, "tome");
					since_id = timelineEntries.get(0).getId();
				}
				break;
			case 2:
				isLoading = false;
				timeline = weiboManager.getCommentsTimeline(AppContext.comment_timeline_byme, count, page, since_id);
				newTimelineEntries = timeline.getComments();
				if (newTimelineEntries != null && !newTimelineEntries.isEmpty()) {
					List<CommentEntry> temp = new ArrayList<CommentEntry>(timelineEntries);
					timelineEntries.clear();
					timelineEntries.addAll(newTimelineEntries);
					timelineEntries.addAll(temp);
					table.save(timelineEntries, "byme");
					since_id = timelineEntries.get(0).getId();
				}
				break;
			case 3:
			isLoading = false;
			timeline = weiboManager.getCommentsTimeline(AppContext.comment_timeline_mentionme, count, page, since_id);
			newTimelineEntries = timeline.getComments();
			if (newTimelineEntries != null && !newTimelineEntries.isEmpty()) {
				List<CommentEntry> temp = new ArrayList<CommentEntry>(timelineEntries);
				timelineEntries.clear();
				timelineEntries.addAll(newTimelineEntries);
				timelineEntries.addAll(temp);
				table.save(timelineEntries, "mentionme");
				since_id = timelineEntries.get(0).getId();
			}
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void loadMoreTimeline() {
		try {
			CommentGson timeline = null;
			List<CommentEntry> moreEntries = null;
			page = 1;
			switch (((MainActivity) getActivity()).groupItem) {
			case 0:
				isLoading = false;
				timeline = weiboManager.getCommentsTimeline(AppContext.comment_timeline, count, page, "0");
				moreEntries = timeline.getComments();
				timelineEntries.addAll(moreEntries);
				break;
			case 1:
				isLoading = false;
				timeline = weiboManager.getCommentsTimeline(AppContext.comment_timeline_tome, count, page, "0");
				moreEntries = timeline.getComments();
				timelineEntries.addAll(moreEntries);
				break;
			case 2:
				isLoading = false;
				timeline = weiboManager.getCommentsTimeline(AppContext.comment_timeline_byme, count, page, "0");
				moreEntries = timeline.getComments();
				timelineEntries.addAll(moreEntries);
				break;
			case 3:
				isLoading = false;
				timeline = weiboManager.getCommentsTimeline(AppContext.comment_timeline_mentionme, count, page, "0");
				moreEntries = timeline.getComments();
				timelineEntries.addAll(moreEntries);
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case get_comments_timeline:
			isLoading = true;
			if (timelineEntries != null && !timelineEntries.isEmpty()) {
				adapter = new CommentTimelineAdapter(getActivity(), timelineEntries, listView);
				listView.setAdapter(adapter);
			}
			listView.onRefreshComplete();
			break;
		case load_more:
			isLoading = true;
			adapter.notifyDataSetChanged();
			listView.setSelection(timelineEntries.size() - count);
			listView.onLoadComplete();
			break;
		default:
			break;
		}
		return false;
	}
	
	@Override
	public void onResume() {
		super.onResume();
		if (isLoading) {
			((MainActivity) getActivity()).loadFinish();
		} else {
			((MainActivity) getActivity()).loading();
		}
		localView.removeAllViews();
		localView.addView(listView);
	}
	
}
